import React, {Component} from 'react';
import Topic from './components/Topic'
import List from './components/List'
import Recommend from './components/Recommend'
import Writer from './components/Writer'
import {connect} from 'react-redux'
import {actionCreators} from './store/index'
import {
    HomeWrapper,
    HomeLeft,
    HomeRight,
    BackTop,
} from './style'
class Home extends Component {

    componentDidMount() {
        this.props.changeHomeData();
        this.bindEvents();
        // axios.get('/api/home.json').then((res)=>{
        //     const result = res.data.data;
        //     // console.log(result)
        //     const action = {
        //         type: 'change_home_data',
        //         topicList: result.topicList,
        //         articleList: result.articleList,
        //         recommendList: result.recommendList,
        //     }
        //     this.props.changeHomeData(action);
        // }) 
    }

    componentWillUnmount(){
        window.removeEventListener('scroll', this.props.changeScrollTopShow)
    }

    bindEvents(){
        window.addEventListener('scroll', this.props.changeScrollTopShow)
    }

    handleScrollTop() {
        window.scrollTo(0, 0);
    }

    render() {
        return (
            <HomeWrapper>
                <HomeLeft>
                    <img className='banner-img' src="https://img.tupianzj.com/uploads/allimg/202008/9999/01049f376a.jpg"/>
                    <Topic/>
                    <List/>
                </HomeLeft>
                <HomeRight>
                    <Recommend/>
                    <Writer/>
                </HomeRight>
                {this.props.showScroll ? <BackTop onClick={this.handleScrollTop}>回到顶部</BackTop> : null}
                
            </HomeWrapper>
        )
    }
}

const mapStateToProps =(state) => ({
    showScroll: state.get('home').get('showScroll'),
});

const mapDispatchToProps =(dispatch) => ({
    changeHomeData() {
        const action = actionCreators.getHomeInfo();
        dispatch(action); // 派发action给store,store会自动交给reducer
        // axios.get('/api/home.json').then((res)=>{
        //     const result = res.data.data;
        //     const action = {
        //         type: 'change_home_data',
        //         topicList: result.topicList,
        //         articleList: result.articleList,
        //         recommendList: result.recommendList,
        //     }
        //     dispatch(action);
        // }) 
    },
    changeScrollTopShow(e) {
        // console.log(document.documentElement.scrollTop)
        if(document.documentElement.scrollTop > 400) {
            dispatch(actionCreators.toggleTopShow(true));
        }else {
            dispatch(actionCreators.toggleTopShow(false));
        }
    }
})
export default connect(mapStateToProps, mapDispatchToProps)(Home);